package cn.com.victorysoft.ylgl.service.commons.mybatis.mapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/***
 * @author gechaoqing
 */
public class Sort {
    public static final Direction DEFAULT_DIRECTION = Direction.ASC;
    private List<Order> orders;

    public Sort(Order... orders) {
        this(Arrays.asList(orders));
    }

    public Sort(List<Order> orders) {
        if ((null == orders) || (orders.isEmpty())) {
            throw new IllegalArgumentException("你必须指定一个排序属性！");
        }
        this.orders = orders;
    }

    public Sort(String... properties) {
        this(DEFAULT_DIRECTION, properties);
    }

    public Sort(Direction direction, String... properties) {
        this(direction, properties == null ? new ArrayList<>() : Arrays.asList(properties));
    }

    public Sort(Direction direction, List<String> properties) {
        if ((properties == null) || (properties.isEmpty())) {
            throw new IllegalArgumentException("你必须指定一个排序属性！");
        }
        this.orders = new ArrayList<>(properties.size());
        for (String property : properties) {
            this.orders.add(new Order(direction, property));
        }
    }

    public Iterator<Order> iterator() {
        return this.orders.iterator();
    }

    @Override
    public String toString() {
        return "Sort{orders=" + this.orders + '}';
    }

    public static class Order {
        private final Sort.Direction direction;
        private final String property;

        public Order(Sort.Direction direction, String property) {
            this.direction = direction;
            this.property = property;
        }

        public Sort.Direction getDirection() {
            return this.direction;
        }

        public String getProperty() {
            return this.property;
        }

        @Override
        public String toString() {
            return "Order{direction=" + this.direction + ", property='" + this.property + '\'' + '}';
        }
    }

    /***
     * 排序
     */
    public enum Direction {
        /***
         * 升序
         */
        ASC,
        /***
         * 降序
         */
        DESC;

        Direction() {
        }

        public static Direction fromString(String value) {
            try {
                return valueOf(value.toUpperCase());
            } catch (Exception e) {
                throw new IllegalArgumentException(String.format("'%s' 为无效值! 能识别的有效值为 'desc' 或 'asc' .", value), e);
            }
        }

        public static Direction fromStringOrNull(String value) {
            try {
                return fromString(value);
            } catch (IllegalArgumentException e) {
                return null;
            }
        }
    }
}
